
import './index.scss';

class Calendar extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      open: false,
      calendarHeight: 0,
      xY: '',
      only: true,
      activeRow: 0,
      HTML: false,
      target: false,
      time: `${this.props.date.getFullYear()}-${this.props.date.getMonth() + 1 < 10 ? '0' + (this.props.date.getMonth() + 1): this.props.date.getMonth() + 1}`
    }
  }

  // DOM树渲染前
  componentWillMount() {
    this.setState({
      xY:[],
      HTML: this.makeCalendar(this.props.date)
    });
  }

  activeRow(DateObj) {
    let cloneDateObj = new Date(DateObj.getTime());
    let time  = {
      days: cloneDateObj.getDate(),
      week: cloneDateObj.getDay(),
      firstDay: new Date(cloneDateObj.setDate(1)),
      xy: {
        x: 0,
        y: 0
      }
    }
    time.firstDatWeek = time.firstDay.getDay();
    let firstDatWeek = time.days - (7 - (time.firstDatWeek === 0 ? 7 : time.firstDatWeek));
    if (firstDatWeek < 1) {
      console.log(1);
      time.xy.x = time.week - time.firstDatWeek;
      time.xy.y = 0;
    } else {
      console.log(firstDatWeek);
      time.xy.x = time.week;
      if (firstDatWeek % 7 === 0) {
          time.xy.y = firstDatWeek / 7 - 1;
        } else {
          time.xy.y = firstDatWeek < 1 ? Math.floor(firstDatWeek / 7) - 1 :  Math.floor(firstDatWeek / 7) + 1;
        }
    }
    console.log(time.xy);
    return time.xy;
  }

  componentDidMount () {
    // 记录天数的高度=>动画
    if (this.state.HTML) {
      if (this.state.only) {
        let state = this.state;
        state.active = this.activeRow(this.props.date);
        this.refs.calendar.style.height = `${state.calendarTitle + state.rowHeight + state.weekHeight}px`;
        state.calendarHeight = this.refs.calendar.children[0].clientHeight;
        state.rowHeight = this.refs.day.children[0].clientHeight;
        state.calendarTitle = this.refs.title.clientHeight;
        state.weekHeight = this.refs.week.clientHeight;
        state.target = this.refs.day.childNodes[state.active.y].childNodes[state.active.x].childNodes[0];
        state.target.className = 'active';
        this.refs.day.style.transform = `translateY(-${state.active.y * state.rowHeight}px)`;
        this.setState({
          only: false,
          activeRow: this.state.active.y
        })
      }
    }
  }



  // 制作日历
  makeCalendar(DateObj) {
    // 计算这个月的第一天和最后一天
    let firstDaylastDay = function(DateObj) {
      let cloneDateObj = new Date(DateObj.getTime()),
          month = cloneDateObj.getMonth();
      return {
        first: new Date(cloneDateObj.setDate(1)),
        last: new Date(new Date(cloneDateObj.setMonth(month + 1)).setDate(1)-86400000)
      };
    };

    // 计算这个月以七天为一行所要的行数
    let weekRows = function(DateObj) {
      let time = {
          week: DateObj.first.getDay(),
          days: DateObj.last.getDate()
        };
      time.sunday = time.week === 0 ? true : false;
      time.days = time.days-(7-time.sunday === 0 ? 7 : time.sunday);
      if (time.days % 7 !== 0) {
        return time.sunday ? Math.floor(time.days / 7) + 1 :  Math.floor(time.days / 7) + 2
      } else {
        return time.sunday === 0 ? time.days / 7 : time.days / 7 + 1;
      }
    };


    // 绘制这个月的每一天
    let makeDay =  function(DateObj, rows) {
      let time = {
        days: DateObj.last.getDate(),
        week: DateObj.first.getDay(),
        num: 0,
        make: []
      };
      for (let i = 0, l = rows; i < l ; i += 1) {
        let day = [];
        day.push(`<ul data-row="${i}">`);

        for (let ii = 0; ii < 7; ii += 1) {
          time.week !== 0 && (ii = time.week, time.week = 0);
          day.push(`<li><span>${++time.num}</span></li>`);
          if (time.num >= time.days) {
            break;
          }
        }
        day.push('</ul>');
        time.make[time.make.length] = day.join('');
      }
      return time.make.join('');
    }

    let cloneDateObj = firstDaylastDay(DateObj);

    return makeDay(cloneDateObj, weekRows(cloneDateObj));
  }

  // 记录触摸屏幕的起始坐标
  touchstart(E) {
    this.state.xy = [E.touches[0].clientX, E.touches[0].clientY];
    E.preventDefault();
  }

  touchend(E) {
    let x = this.state.xy[0] - E.changedTouches[0].clientX,
        y = this.state.xy[1] - E.changedTouches[0].clientY;

    slippageX.call(this, x, y);

    // 左右滑动
    function slippageX(x, y) {
      let translatex = this.refs.day.style.transform;
      translatex = translatex !== '' ? translatex.slice(11,-3) : 0;
      if (150 < x || x < -150) {
        this.refs.day.style.transition = '';
        this.refs.day.style.transform = `translateX(${this.state.active.y}vw)`;

        // 判断是否展开
        if(!this.state.open) {
          this.refs.day.style.width = '600vw';
          this.refs.day.className = 'calendar-day single';
        }

        if (150 < x) {
          this.refs.day.style.transform = `translateX(${+translatex - 100}vw)`;
        } else {
          this.refs.day.style.transform = `translateX(${+translatex + 100}vw)`;
        }
      } else {
        slippageY.call(this, y)
      }
    }

    // 上下滑动
    function slippageY(y){
      if ( y > 30 || y < -30) {
        this.refs.day.style.width = '100vw';
        this.refs.day.className = 'calendar-day';
        this.refs.day.style.transition = 'transform 1s';
        if (y > 30) { // 向上滑动
          this.refs.day.style.transform = `translateY(${-this.state.activeRow * this.state.rowHeight}px)`;
          this.state.open = false;
          this.refs.calendar.style.height = `${this.state.calendarTitle + this.state.rowHeight + this.state.weekHeight}px`;
        } else { // 向下滑动
          this.refs.day.style.transform = '';
          this.state.open = true;
          this.refs.calendar.style.height = `${this.state.calendarHeight}px`;
        }
      }
    }

    E.preventDefault();
  }

  dayClick(E) {
    if(E.target.nodeName === 'SPAN') {
      // 记录被激活的行数=> 动画
      this.state.activeRow = E.target.parentElement.parentElement.dataset.row;
      // 缓存上次目标
      this.setState({
        target: E.target
      });
      // 如果上次目标被记录
      this.state.target && (
        this.state.target.className = '',
        E.target.className = 'active'
      );
    }
  }

  mousedown(E) {
    E.preventDefault()
  }

  mouseup(E) {
    E.preventDefault()
  }

  mousemove(E) {
    E.preventDefault()
  }

  click(E) {
    E.preventDefault()
  }
  render() {
    return (
      <div className="calendar single" ref="calendar" onMouseDown={this.mousedown.bind(this)} onMouseUp={this.mouseup.bind(this)} onMouseMove={this.mousemove.bind(this)} onClick={this.click.bind(this)}>
        <div className="calendar-mobile" onTouchStart={this.touchstart.bind(this)} onTouchEnd={this.touchend.bind(this)}>
          <p className="calendar-title" ref='title' dangerouslySetInnerHTML={{__html: this.state.time}}></p>
          <ul className="calendar-week" ref="week">
            <li>周日</li>
            <li>周一</li>
            <li>周二</li>
            <li>周三</li>
            <li>周四</li>
            <li>周五</li>
            <li>周六</li>
          </ul>
          { this.state.HTML ? <div className="calendar-day" ref="day" onTouchStart={this.dayClick.bind(this)} dangerouslySetInnerHTML={{ __html: this.state.HTML}}></div> :''}
        </div>
      </div>
    )
  }
}

export default Calendar;
